package xyz.jcat.web.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import xyz.jcat.common.util.CollectionUtils;

import java.util.Collection;
import java.util.Objects;

public class RoleAccessDecisionManager implements AccessDecisionManager {

    /**
     *
     * @param authentication 包含了当前的用户信息，包括拥有的权限。这里的权限来源就是前面登录时UserDetailsService中设置的authorities。
     * @param object 就是FilterInvocation对象，可以得到request等web资源
     * @param configAttributes 本次访问需要的权限
     * object being invoked
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if(CollectionUtils.isEmpty(configAttributes)) {
            return;
        }else {
            for(ConfigAttribute role : configAttributes) {
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                for(GrantedAuthority authority : authorities) {
                    if(Objects.equals(authority.getAuthority(), role.getAttribute())) {
                        return;
                    }
                }
            }
            throw new AccessDeniedException("无访问权限");
        }
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
